package net.jueb.custom.server;

import net.jueb.custom.pojo.NError;
import net.jueb.custom.pojo.NMsg;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;

public class ServerHandler extends ChannelHandlerAdapter{
	InternalLogger log=Log4JLoggerFactory.getInstance(this.getClass());
	private int count;
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		if(msg instanceof NError)
		{
			NError error=(NError)msg;
			log.error(error.toString());
			return ;
		}
		
		NMsg nmsg=(NMsg)msg;
		if(nmsg==null)
		{
			log.error("NMsg is NULL");
			return;
		}
		
		count++;
		log.info("count="+count+",收到客户端请求,长度:"+nmsg.pojoData.length);
		String response="count="+count+",长度:"+nmsg.pojoData.length;
		nmsg.pojoData=response.getBytes();
		ctx.writeAndFlush(nmsg);
		log.info("server nmsg is write,count="+count);
		
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
